const fs = require('fs')
const path = require('path')
const marked = require('marked')
const puppeteer = require('puppeteer')

/**
 * 将指定路径对应的文件转换为图片
 * @param {string} input 输入 md 文件路径
 * @param {object} options 选项
 * @param {string} options.output 输出图片路径
 * @param {number} options.width 输出图片路径
 */
module.exports = async (input, options) => {
  if (typeof input !== 'string') {
    throw new TypeError(`Expected a string, got ${typeof name}`)
  }

  // options = options ?? {}
  options = Object.assign({ width: 800 }, options)
  // options = { width: 800, ...options }

  try {
    // 0. 确认文件的存在与否
    const stat = fs.statSync(input) // 如果是相对路径，就是基于 process.cwd()
    if (!stat.isFile()) throw new Error('指定路径不是一个文件')

    // 1. 拿到 md 文件的内容
    const contents = fs.readFileSync(input, 'utf8')

    // 2. md 转换为 html
    const html = marked(contents)

    const fullDocument = `
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <!-- <link rel="stylesheet" href="https://unpkg.com/github-markdown-css"> -->
  <link rel="stylesheet" href="https://cdn.zce.me/markdown.css">
</head>
<body class="markdown-body">
  ${html}
</body>
</html>
    `

    // 3. html 渲染后的结果生产 png
    const browser = await puppeteer.launch() // 后台启动一个浏览器
    const page = await browser.newPage() // 新启一个选项卡
    await page.setViewport({ width: options.width, height: 10 })
    // await page.goto('https://baidu.com')
    await page.setContent(fullDocument)
    await page.screenshot({ fullPage: true, path: 'output.png' })
    await browser.close()
  } catch (e) {
    console.error(e.message)
  }
}
